package com.cma.cmabackend.controller;

import com.cma.cmabackend.entity.Equipment;
import com.cma.cmabackend.service.EquipmentService;
import com.cma.cmabackend.util.EquipmentParser;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RequestMapping("/equipment")
@RestController
@Slf4j
public class EquipmentController {
    @Resource
    EquipmentService equipmentService;

    /**
     * 添加设备
     *
     * @param new_equipment 新设备
     * @return 是否成功
     */
    @PostMapping("/add")
    public Map<String, Object> addEquipment(Equipment new_equipment) {
        return equipmentService.addEquipment(new_equipment);
    }

    /**
     * 设备分页查询
     *
     * @param page         当前页面
     * @param per_page_num 每页个数
     * @return 页面对象
     */
    @GetMapping("/get")
    public Map<String, Object> pageQuery(int page, int per_page_num) {
        Map<String, Object> result = new HashMap<>();
        Page<Equipment> equipmentPage = equipmentService.pageQuery(page, per_page_num);
        result.put("content", equipmentPage.getContent());
        result.put("last", equipmentPage.isLast());
        result.put("first", equipmentPage.isFirst());
        result.put("totalPages", equipmentPage.getTotalPages());
        return result;
    }

    @GetMapping("/getall")
    public List<Equipment> getAll() {
        return equipmentService.getAll();
    }

    /**
     * 接收上传的文件并把数据存入数据库
     *
     * @param file 上传的文件
     * @return 是否成功
     */
    @PostMapping("/file")
    public Map<String, Object> upload(MultipartFile file) throws IOException {
        Map<String, Object> result = new HashMap<>();
        //解析excel表格到设备类的列表
        List<Equipment> equipmentList = EquipmentParser.parseEquipment(file);

        equipmentService.addEquipments(equipmentList);

        result.put("success", true);
        return result;
    }
}
